<template>
  <el-row :gutter="24">
    <el-col :span="4">
      <div class="nav">
        <div class="title1">商品类型列表</div>
        <div class="tree">
          <TreeProduct @sendTreeDate="sendTreeDate"> </TreeProduct>
        </div>
      </div>
    </el-col>
    <el-col :span="20">
      <div class="wrapper">
        <div class="title2">商品{{ title }}</div>
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="所属分类" prop="category"
            >{{ ruleForm.category }}
          </el-form-item>
          <el-form-item label="商品名称" prop="title">
            <el-input v-model="ruleForm.title"></el-input>
          </el-form-item>
          <el-form-item label="商品价格" prop="price">
            <el-input v-model="ruleForm.price"></el-input>
          </el-form-item>
          <el-form-item label="商品数量" prop="num">
            <el-input v-model="ruleForm.num"></el-input>
          </el-form-item>
          <el-form-item label="商品卖点" prop="sellPoint">
            <el-input v-model="ruleForm.sellPoint"></el-input>
          </el-form-item>
          <el-form-item label="上传图片" prop="image">
            <UploadImg
              @sendImg="sendImg"
              ref="uploadImg"
              :fileList="fileList"
            ></UploadImg>
          </el-form-item>
          <el-form-item label="商品描述" prop="descs">
            <WangEditor
              @sendWangEditor="sendWangEditor"
              ref="wangEditor"
            ></WangEditor>
          </el-form-item>

          <el-form-item label="首页轮播推荐" prop="isShow">
            <el-switch v-model="ruleForm.isShow"></el-switch>
          </el-form-item>
          <el-form-item label="是否推荐商品" prop="isShow">
            <el-switch v-model="ruleForm.isShow"></el-switch>
          </el-form-item>
          <el-form-item label="是否上架商品" prop="isShow">
            <el-switch v-model="ruleForm.isShow"></el-switch>
          </el-form-item>

          <el-form-item>
            <el-button v-show="title!='详情'" type="primary" @click="submitForm('ruleForm')"
              >保存</el-button
            >
            <el-button v-show="title!='详情'" @click="resetForm('ruleForm')">重置</el-button>
            <el-button @click="closePage('ruleForm')">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-col>
  </el-row>
</template>

<script>
import TreeProduct from "./TreeProduct.vue";
import UploadImg from "./UploadImg.vue";
import WangEditor from "./WangEditor.vue";
import { mapState } from "vuex";

export default {
  components: { TreeProduct, UploadImg, WangEditor },
  computed: {
    ...mapState("product", ["rowdata", "title"]),
  },
  mounted() {
    if (this.title == "编辑"||this.title=="详情") {
      console.log("---编辑");
      //这里将地址赋值改为属性赋值
      //this.ruleForm = {...this.rowdata};//浅拷贝
      this.ruleForm = JSON.parse(JSON.stringify(this.rowdata));
      this.ruleForm.isShow = true;
      let imgs = this.ruleForm.image; //字符串类型
      //转数组
      let arr = JSON.parse(imgs);
      this.ruleForm.image = arr;
      //将数组传给子组件UploadImg的fileList

      arr.forEach((element) => {
        this.fileList.push({ name: "", url: element });
      });

      //WangEditor 不能放在Created 生命周期内， 只能在mounted里面拿到
      console.log("wangEditor----", this.$refs.wangEditor);
      this.$nextTick(() => {
        this.$refs.wangEditor.html = this.rowdata.descs;
      });
    }
  },

  data() {
    return {
      fileList: [], //图片容器
      ruleForm: {
        //表单数据
        id: "",
        title: "",
        num: "",
        price: "",
        sellPoint: "",
        image: [],
        descs: "",
        category: "",
        cid: "",
        isShow: true,
      },
      rules: {
        //表单验证规则
        title: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
          //{ min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        num: [{ required: true, message: "请输入商品数量", trigger: "change" }],
        price: [
          { required: true, message: "请输入商品价格", trigger: "change" },
        ],
        category: [
          { required: true, message: "请选择商品类目", trigger: "change" },
        ],
      },
    };
  },
  methods: {
    //接受上传图片的回调方法，
    sendImg(val) {
      console.log(val);
      this.ruleForm.image.push(val);
      console.log(this.ruleForm);
    },
    //接受富文本编辑器的数据
    sendWangEditor(val) {
      console.log(val);
      this.ruleForm.descs = val;
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //结构赋值
          let {
            id,
            title,
            image,
            sellPoint,
            price,
            cid,
            category,
            num,
            descs,
          } = this.ruleForm;
          if (this.title == "添加") {
            console.log("添加商品------", this.ruleForm);
            //image 数组转字符串
            this.insertTbItem({
              title,
              image: JSON.stringify(image),
              sellPoint,
              price,
              cid,
              category,
              num,
              descs,
            });
          } else {
            //商品修改逻辑
            console.log("商品修改", this.ruleForm);
            //调服务器端修改接口
            this.updateTbItem({
              id,
              title,
              image: JSON.stringify(image),
              sellPoint,
              price,
              cid,
              category,
              num,
              descs,
            });
          }
        } else {
          console.log("表单校验出错!!");
          return false;
        }
      });
    },

    //修改商品接口
    async updateTbItem(params) {
      console.log("param-----", params);
      let res = await this.$api.updateTbItem(params);
      console.log("res-----", res);
      if (res.data.status === 200) {
        this.$message({
          message: "修改商品成功",
          type: "success",
        });
        //跳转到列表页
        this.$router.push("/product/list");
      }
    },

    //添加商品
    async insertTbItem(params) {
      let res = await this.$api.insertTbItem(params);
      if (res.data.status === 200) {
        this.$message({
          message: "添加商品成功",
          type: "success",
        });
        //跳转到列表页
        this.$router.push("/product/list");
      }
    },
    resetForm(formName) {
      if (this.title == "添加") {
        this.$refs[formName].resetFields();
        //清空图片列表--调用子组件的方法
        this.$refs.uploadImg.clear();
        //清空富文本
        this.$nextTick(() => {
          this.$refs.wangEditor.html = "";
        });
      } else {
        //编辑界面的重置操作
        //回复之前的默认值, vuex中的store中的值rowdata
        //重置文本框内容
        this.ruleForm = JSON.parse(JSON.stringify(this.rowdata));
        //重置图片
        let rowData = JSON.parse(JSON.stringify(this.rowdata));
        let imgs = rowData.image; //字符串类型
        let arr = JSON.parse(imgs);
        this.ruleForm.image = arr;
        this.fileList = [];
        arr.forEach((element) => {
          this.fileList.push({ name: "", url: element });
        });
        //重置富文本
        this.$nextTick(() => {
          this.$refs.wangEditor.html = rowData.descs;
        });
      }
    },
    closePage(){
      this.$router.push('/product/list')
    },

    //获取子组件tree点击的数据
    sendTreeDate(val) {
      this.ruleForm.category = val.name;
      this.ruleForm.cid = val.cid;
    },
  },
};
</script>

<style lang="less" scoped>
.nav {
  height: 600px;
  background: #fff;
  .title1 {
    background: skyblue;
    padding: 20px;
    color: #fff;
  }
  .tree {
    padding: 20px;
  }
}
.wrapper {
  background: #fff;
  .title2 {
    background: #ccc;
    padding: 14px;
    color: #333;
    font-weight: bold;
  }
  .demo-ruleForm {
    padding: 30px;
  }
}
</style>